const fs = require('fs').promises;
const path = require('path');
const { v4: uuidv4 } = require('uuid');
const logger = require('../utils/logger');
const familyMemberModel = require('../models/familyMember');

// 数据文件路径
const FAMILY_FILE = path.join(__dirname, '../data/family.json');

// 确保数据文件存在
const ensureDataFile = async () => {
  try {
    // 确保目录存在
    const dataDir = path.dirname(FAMILY_FILE);
    await fs.mkdir(dataDir, { recursive: true });
    
    // 检查文件是否存在
    try {
      await fs.access(FAMILY_FILE);
    } catch (error) {
      // 文件不存在，创建空数组文件
      await fs.writeFile(FAMILY_FILE, JSON.stringify([], null, 2));
      logger.info(`创建家人数据文件: ${FAMILY_FILE}`);
    }
  } catch (error) {
    logger.error(`确保数据文件存在时出错: ${error.message}`);
    throw error;
  }
};

// 读取家人数据
const readFamilyData = async () => {
  await ensureDataFile();
  
  try {
    const data = await fs.readFile(FAMILY_FILE, 'utf8');
    return JSON.parse(data);
  } catch (error) {
    logger.error(`读取家人数据失败: ${error.message}`);
    throw new Error(`读取家人数据失败: ${error.message}`);
  }
};

// 写入家人数据
const writeFamilyData = async (data) => {
  try {
    await fs.writeFile(FAMILY_FILE, JSON.stringify(data, null, 2));
  } catch (error) {
    logger.error(`写入家人数据失败: ${error.message}`);
    throw new Error(`写入家人数据失败: ${error.message}`);
  }
};

/**
 * 获取所有家人信息
 * @param {Object} req - Express请求对象
 * @param {Object} res - Express响应对象
 */
exports.getAllFamilyMembers = async (req, res) => {
  try {
    const familyMembers = await readFamilyData();
    
    res.json({
      success: true,
      data: familyMembers
    });
  } catch (error) {
    logger.error(`获取所有家人信息失败: ${error.message}`);
    res.status(500).json({
      success: false,
      message: '获取家人信息失败',
      error: error.message
    });
  }
};

/**
 * 获取单个家人信息
 * @param {Object} req - Express请求对象
 * @param {Object} res - Express响应对象
 */
exports.getFamilyMember = async (req, res) => {
  try {
    const id = req.params.id;
    const familyMembers = await readFamilyData();
    
    const familyMember = familyMembers.find(member => member.id === id);
    
    if (!familyMember) {
      return res.status(404).json({
        success: false,
        message: '未找到指定家人信息'
      });
    }
    
    res.json({
      success: true,
      data: familyMember
    });
  } catch (error) {
    logger.error(`获取家人信息失败: ${error.message}`);
    res.status(500).json({
      success: false,
      message: '获取家人信息失败',
      error: error.message
    });
  }
};

/**
 * 添加家人信息
 * @param {Object} req - Express请求对象
 * @param {Object} res - Express响应对象
 */
exports.addFamilyMember = async (req, res) => {
  try {
    // 验证数据
    const validation = familyMemberModel.validate(req.body);
    if (!validation.isValid) {
      return res.status(400).json({
        success: false,
        message: '家人信息数据无效',
        errors: validation.errors
      });
    }
    
    // 读取现有数据
    const familyMembers = await readFamilyData();
    
    // 创建新家人信息
    const newMember = familyMemberModel.create({
      ...req.body,
      id: uuidv4(),
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString()
    });
    
    // 添加到数组
    familyMembers.push(newMember);
    
    // 保存数据
    await writeFamilyData(familyMembers);
    
    res.status(201).json({
      success: true,
      message: '家人信息添加成功',
      data: newMember
    });
  } catch (error) {
    logger.error(`添加家人信息失败: ${error.message}`);
    res.status(500).json({
      success: false,
      message: '添加家人信息失败',
      error: error.message
    });
  }
};

/**
 * 更新家人信息
 * @param {Object} req - Express请求对象
 * @param {Object} res - Express响应对象
 */
exports.updateFamilyMember = async (req, res) => {
  try {
    const id = req.params.id;
    
    // 验证数据
    const validation = familyMemberModel.validate(req.body);
    if (!validation.isValid) {
      return res.status(400).json({
        success: false,
        message: '家人信息数据无效',
        errors: validation.errors
      });
    }
    
    // 读取现有数据
    const familyMembers = await readFamilyData();
    
    // 查找要更新的家人
    const index = familyMembers.findIndex(member => member.id === id);
    
    if (index === -1) {
      return res.status(404).json({
        success: false,
        message: '未找到指定家人信息'
      });
    }
    
    // 更新家人信息
    const updatedMember = familyMemberModel.create({
      ...familyMembers[index],
      ...req.body,
      id, // 保持ID不变
      updatedAt: new Date().toISOString()
    });
    
    familyMembers[index] = updatedMember;
    
    // 保存数据
    await writeFamilyData(familyMembers);
    
    res.json({
      success: true,
      message: '家人信息更新成功',
      data: updatedMember
    });
  } catch (error) {
    logger.error(`更新家人信息失败: ${error.message}`);
    res.status(500).json({
      success: false,
      message: '更新家人信息失败',
      error: error.message
    });
  }
};

/**
 * 删除家人信息
 * @param {Object} req - Express请求对象
 * @param {Object} res - Express响应对象
 */
exports.deleteFamilyMember = async (req, res) => {
  try {
    const id = req.params.id;
    
    // 读取现有数据
    const familyMembers = await readFamilyData();
    
    // 查找要删除的家人
    const index = familyMembers.findIndex(member => member.id === id);
    
    if (index === -1) {
      return res.status(404).json({
        success: false,
        message: '未找到指定家人信息'
      });
    }
    
    // 如果有头像，尝试删除头像文件
    const member = familyMembers[index];
    if (member.avatar && member.avatar.startsWith('uploads/')) {
      try {
        const avatarPath = path.join(__dirname, '..', member.avatar);
        await fs.unlink(avatarPath);
        logger.info(`删除头像文件: ${avatarPath}`);
      } catch (unlinkError) {
        logger.warn(`删除头像文件失败: ${unlinkError.message}`);
        // 继续处理，不影响删除操作
      }
    }
    
    // 删除家人信息
    familyMembers.splice(index, 1);
    
    // 保存数据
    await writeFamilyData(familyMembers);
    
    res.json({
      success: true,
      message: '家人信息删除成功'
    });
  } catch (error) {
    logger.error(`删除家人信息失败: ${error.message}`);
    res.status(500).json({
      success: false,
      message: '删除家人信息失败',
      error: error.message
    });
  }
};

/**
 * 上传家人头像
 * @param {Object} req - Express请求对象
 * @param {Object} res - Express响应对象
 */
exports.uploadAvatar = async (req, res) => {
  try {
    const id = req.params.id;
    
    // 检查是否有文件上传
    if (!req.file) {
      return res.status(400).json({
        success: false,
        message: '未上传头像文件'
      });
    }
    
    // 读取现有数据
    const familyMembers = await readFamilyData();
    
    // 查找要更新的家人
    const index = familyMembers.findIndex(member => member.id === id);
    
    if (index === -1) {
      // 删除上传的文件
      try {
        await fs.unlink(req.file.path);
      } catch (unlinkError) {
        logger.warn(`删除临时文件失败: ${unlinkError.message}`);
      }
      
      return res.status(404).json({
        success: false,
        message: '未找到指定家人信息'
      });
    }
    
    // 获取文件的相对路径（用于存储和访问）
    const relativePath = path.relative(path.join(__dirname, '..'), req.file.path).replace(/\\/g, '/');
    
    // 如果已有头像，尝试删除旧头像文件
    const member = familyMembers[index];
    if (member.avatar && member.avatar.startsWith('uploads/')) {
      try {
        const oldAvatarPath = path.join(__dirname, '..', member.avatar);
        await fs.unlink(oldAvatarPath);
        logger.info(`删除旧头像文件: ${oldAvatarPath}`);
      } catch (unlinkError) {
        logger.warn(`删除旧头像文件失败: ${unlinkError.message}`);
        // 继续处理，不影响更新操作
      }
    }
    
    // 更新头像路径
    member.avatar = relativePath;
    member.updatedAt = new Date().toISOString();
    
    // 保存数据
    await writeFamilyData(familyMembers);
    
    res.json({
      success: true,
      message: '头像上传成功',
      data: {
        avatar: relativePath
      }
    });
  } catch (error) {
    logger.error(`上传头像失败: ${error.message}`);
    res.status(500).json({
      success: false,
      message: '上传头像失败',
      error: error.message
    });
  }
};